package service

import (
	"context"
	"errors"
	"video_src/basic/appConfig"
	__ "video_src/basic/proto"
	"video_src/handler/models"
)

func (s *Server) EpisodeList(_ context.Context, in *__.EpisodeListReq) (*__.EpisodeListResp, error) {
	var ep models.Episode
	var epList []*__.ListEpisode

	lists, err := ep.EpisodeList(appConfig.DB)
	if err != nil {
		return nil, err
	}

	for _, e := range lists {
		list := __.ListEpisode{
			Title:     e.Title,
			EpisodeNo: e.EpisodeNo,
			Long:      e.Long,
		}
		epList = append(epList, &list)
	}

	return &__.EpisodeListResp{
		List: epList,
	}, nil
}

func (s *Server) CreatePlayRecord(_ context.Context, in *__.CreatePlayRecordReq) (*__.CreatePlayRecordResp, error) {
	var err error
	var pr models.PlayRecord

	pr.VideoId = in.VideoId
	pr.EpisodeId = in.Episode
	pr.UserId = in.UserId
	pr.Seconds = in.Seconds
	if err = pr.AddPlayRecord(appConfig.DB); err != nil {
		return nil, errors.New("用户观看历史记录创建失败")
	}

	return &__.CreatePlayRecordResp{
		UserId: in.UserId,
	}, nil
}

func (s *Server) PlayRecordList(_ context.Context, in *__.PlayRecordListReq) (*__.PlayRecordListResp, error) {

	var pr models.PlayRecord
	var prList []*__.PlayRecord

	lists, err := pr.GetEpisodePlayRecordByUserId(appConfig.DB, int(in.UserId))
	if err != nil {
		return nil, err
	}

	for _, p := range lists {
		list := __.PlayRecord{
			VideoId: p.VideoId,
			Episode: p.EpisodeId,
			UserId:  p.UserId,
			Seconds: p.Seconds,
		}
		prList = append(prList, &list)
	}

	return &__.PlayRecordListResp{
		List: prList,
	}, nil
}

func (s *Server) PlayRecordDel(_ context.Context, in *__.PlayRecordDelReq) (*__.PlayRecordDelResp, error) {
	var err error
	var ps models.PlayRecord

	if err = ps.DelPlayRecordByUserId(appConfig.DB, int(in.UserId)); err != nil {
		return nil, errors.New("用户历史记录删除失败")
	}
	return &__.PlayRecordDelResp{
		Msg: "用户历史记录删除失败",
	}, nil
}

func (s *Server) TotalHot(_ context.Context, in *__.TotalHotReq) (*__.TotalHotResp, error) {
	var v models.Video

	hot, err := v.HotTotal(appConfig.DB, in.VideoId)
	if err != nil {

	}
	return &__.TotalHotResp{
		VideoId: in.VideoId,
		Hot:     hot,
	}, nil
}

func (s *Server) TheHot(_ context.Context, in *__.TheHotReq) (*__.TheHotResp, error) {

	var vs models.Video
	var vsList []*__.HotList

	lists, err := vs.VideoList(appConfig.DB)
	if err != nil {
		return nil, err
	}

	for _, v := range lists {
		list := __.HotList{
			VideoId: int64(v.ID),
			Title:   v.Title,
			TypesId: v.TypesId,
			Hot:     v.Hot,
		}
		vsList = append(vsList, &list)
	}
	return &__.TheHotResp{
		List: vsList,
	}, nil
}
